﻿function Matrix (values) {
    this.values = values;
    this.numberOfRows = values.length;
    this.numberOfColumns = values[0].length;
}

Matrix.prototype.transpose = function () {
    var tmp = [];

    for (var i = 0; i < this.numberOfColumns; i++) {
        tmp[i] = [];
    }

    for (var i = 0; i < this.numberOfRows; i++) {
        for (var j = 0; j < this.numberOfColumns; j++) {
            tmp[j][i] = this.values[i][j];
        }
    }

    return new Matrix(tmp);
}

//only for 2x2 matrix
Matrix.prototype.inverse = function () {
    var a = this.values[0][0];
    var b = this.values[0][1];
    var c = this.values[1][0];
    var d = this.values[1][1];

    var multiplier = 1 / (a * d - b * c);

    var tmp = [[], []];

    tmp[0][0] = multiplier * d;
    tmp[0][1] = multiplier * (-b);
    tmp[1][0] = multiplier * (-c);
    tmp[1][1] = multiplier * a;

    return new Matrix(tmp);
}

Matrix.prototype.print = function () {
    for (var i = 0; i < this.numberOfRows; i++) {
        for (var j = 0; j < this.numberOfColumns; j++) {
            document.write(this.values[i][j].toFixed(2) + " ");
        }

        document.writeln("</br>");
    }

    document.writeln("</br>");
    document.writeln("</br>");
}

Matrix.multiply = function (matrixA, matrixB) {
    var tmp = [];

    for (var i = 0; i < matrixA.numberOfRows; i++) {

        tmp[i] = [];
        for (var j = 0; j < matrixB.numberOfColumns; j++) {

            tmp[i][j] = 0;
            for (var k = 0; k < matrixA.numberOfColumns; k++) {
                tmp[i][j] += matrixA.values[i][k] * matrixB.values[k][j];
            }
        }
    }

    return new Matrix(tmp);
}